package offer.twoPointers;

import java.util.ArrayList;

/**
 * @author DengYuan2
 * @create 2021-02-19 22:26
 */
public class n_57_2 {
    public static void main(String[] args) {
        n_57_2 n = new n_57_2();
        ArrayList<ArrayList<Integer>> res = n.FindContinuousSequence2(9);
        System.out.println(res);
    }

    /**
     * 我-枚举
     * @param sum
     * @return
     */
    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        for (int i = 1; i <= sum - 2; i++) {
            int s = 0;
            for (int j = i; j < sum; ) {
                s += j;
                if (s < sum) {
                    j++;
                } else if (s > sum) {
                    break;
                } else {
                    ArrayList<Integer> list = new ArrayList<>();
                    for (int k = i; k <=j ; k++) {
                        list.add(k);
                    }
                    res.add(list);
                }
            }


        }
        return res;
    }

    /**
     * 大神-巧妙利用双指针啊
     * @param sum
     * @return
     */
    public ArrayList<ArrayList<Integer>> FindContinuousSequence2(int sum) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        int start=1;
        int end=2;
        int curSum=3;
        while (end<sum){
            if (curSum<sum){
                end++;
                curSum+=end;
            }else if (curSum>sum){
                curSum-=start;
                start++;
            }else {
                ArrayList<Integer> list = new ArrayList<>();
                for (int i = start; i <=end ; i++) {
                    list.add(i);
                }
                res.add(list);
                curSum-=start;
                start++;
                end++;
                curSum+=end;
            }
        }
        return res;
    }
}
